<template>
  <div class="form_item">
    <div v-if="encrypted" class="encrypted" @click="decryptData(formItem.propName)"><span>●●●●●●</span><i class="el-icon-view" /></div>
    <div v-else-if="formItem.elementType==='file'" :class="formItem.className">
      <template v-if="!formItem.attachHtml||formItem.propName.indexOf('formfile') === -1">
        <validation-provider v-slot="{ errors }" :name="formItem.propComment" :rules="{ required: formItem.isRequired===1, phone: formItem.isPhone, email: formItem.isEmail,number:formItem.isNumber}">
          <el-tooltip :disabled="errors===undefined||errors[0]===undefined" :content="errors===undefined?'':errors[0]" :class="{'invalid-field':errors!==undefined&&errors[0]!==undefined}" popper-class="error-popper-class" placement="right-start" effect="dark">
            <el-upload
              v-if="formItem.elementCanEdit===1"
              ref="upload"
              :on-change="handleUploadChange"
              :on-error="handleUploadError"
              action=""
              :multiple="true"
              :file-list="fileList"
              :show-file-list="false"
              :auto-upload="false"
              :with-credentials="true"
              :accept="formItem.textFormatter"
            >
              <el-input v-model="vo[formItem.nameField]" :name="formItem.nameField" :readonly="true" :placeholder="formItem.emptyMessage" @focus="handleUploadClick">
                <el-button slot="append" icon="el-icon-upload2" @click="handleUploadClick" />
              </el-input>
            </el-upload>
          </el-tooltip>
        </validation-provider>
        <el-divider v-if="formItem.elementCanEdit===1&&formItem.attachHtml>''" />
      </template>
      <span v-html="formItem.attachHtml" />
      <el-link v-if="canEdit===1&&formItem.deleteAttach===1&&formItem.attachHtml" class="removeBodyfileIcon" type="danger" title="删除文件" icon="el-icon-close" :underline="false" @click="removeFormfile(formItem.attachId)" />
    </div>
    <div v-else-if="formItem.elementCanEdit===0 && formItem.elementType!=='html' && !formItem.disabled && formItem.propName!=='resRoles'" :class="formItem.className">
      <span v-if="formItem.textFormatter=='password'">******</span>
      <span v-else-if="formItem.value!=null" v-html="(formItem.dateValue||formItem.value)+formItem.valueSuffix" />
    </div>
    <res-roles v-else-if="formItem.elementType==='checkbox'&&formItem.propName==='resRoles'" :can-edit="canEdit" :res-id="vo.id" :res-type="formItem.resType" :root-org-code="vo.orgCode" :sys-code="vo.sysCode" :permission-code="formItem.permissionCode" :change="handleResRolesChange" />
    <div v-else-if="formItem.elementType==='html'" class="description-text" v-html="formItem.htmlContent" />
    <datetime-range v-else-if="formItem.elementType==='datetimeRange'" :vo="vo" :type="formItem.pickerType" :v-model-start="formItem.vModelStart" :v-model-end="formItem.vModelEnd" :can-edit="canEdit" :placeholder-start="formItem.emptyMessageStart" :placeholder-end="formItem.emptyMessageEnd" :required="formItem.isRequired===1" :format="formItem.textFormatter" />
    <validation-provider
      v-else
      v-slot="{ errors }"
      :name="formItem.propComment"
      :rules="{ required: formItem.isRequired===1, phone: formItem.isPhone, email: formItem.isEmail,min:!formItem.valueMinLength||formItem.valueMinLength===null?false:formItem.valueMinLength,max:!formItem.valueMaxLength||formItem.valueMaxLength===null?false:formItem.valueMaxLength,integer:formItem.isInteger,number:formItem.isNumber,identity:formItem.isIdentity}"
    >
      <el-tooltip :disabled="errors===undefined||errors[0]===undefined" :content="errors===undefined?'':errors[0]" :class="{'invalid-field':errors!==undefined&&errors[0]!==undefined}" popper-class="error-popper-class" placement="right-start" effect="dark">
        <template v-if="formItem.dialog===1">
          <el-input
            v-if="formItem.dialogType==='custom'"
            v-model="formItem.value"
            :class="formItem.elementType==='textarea'?'form_item_textarea':''"
            :dialog-title="formItem.dialogTitle"
            :name="formItem.propName"
            :placeholder="formItem.emptyMessage"
            :type="formItem.elementType"
            :autosize="autosize"
            :readonly="formItem.elementReadonly"
            @change="valueChange"
          >
            <el-button slot="append" icon="el-icon-more" @click="itemOnClick" />
          </el-input>
          <el-input
            v-else-if="formItem.dialogType==='listitem'"
            v-model="formItem.value"
            :class="formItem.elementType==='textarea'?'form_item_textarea':''"
            :name="formItem.propName"
            :placeholder="formItem.emptyMessage"
            :type="formItem.elementType"
            :autosize="autosize"
            :readonly="formItem.elementReadonly"
            @change="valueChange"
          >
            <el-button slot="append" icon="el-icon-more" @click="openListitemDialog" />
          </el-input>
          <el-input
            v-else-if="formItem.dialogType==='listpage'"
            v-model="formItem.value"
            v-listpage-dialog
            :class="formItem.elementType==='textarea'?'form_item_textarea':''"
            :exclude-fields="formItem.dialogExcludeFileds"
            :retain-btns="formItem.dialogRetainBtns"
            :listviewurl="formItem.dialogListviewurl"
            :multiple="formItem.dialogMultiple"
            :dialog-title="formItem.dialogTitle"
            :name="formItem.propName"
            :placeholder="formItem.emptyMessage"
            :type="formItem.elementType"
            :autosize="autosize"
            :readonly="formItem.elementReadonly"
            @change="valueChange"
          />
          <el-input
            v-else
            v-model="formItem.value"
            v-select-dialog="formItem.dialogType"
            :class="formItem.elementType==='textarea'?'form_item_textarea':''"
            :showemail="formItem.dialogShowemail"
            :showmobile="formItem.dialogShowmobile"
            :showaccount="formItem.dialogShowaccount"
            :org-self="formItem.dialogOrgSelf"
            :org-id="formItem.dialogOrgId"
            :sub-org-name="formItem.dialogSubOrgName"
            :root-org-code="formItem.dialogRootOrgCode"
            :org-level="formItem.dialogOrgLevel"
            :node-level="formItem.dialogNLevelFilter"
            :multiple="formItem.dialogMultiple"
            :dialog-title="formItem.dialogTitle"
            :name="formItem.propName"
            :placeholder="formItem.emptyMessage"
            :type="formItem.elementType"
            :autosize="autosize"
            resize="none"
            :readonly="formItem.elementReadonly"
            @change="valueChange"
          />
        </template>
        <el-input v-else-if="formItem.elementType==='input'" v-model="formItem.value" :name="formItem.propName" :show-password="formItem.textFormatter=='password'" :placeholder="formItem.emptyMessage" :readonly="formItem.elementReadonly" :disabled="formItem.disabled" @change="valueChange" @focus="itemOnClick">
          <template slot="suffix"><span class="input_suffix">{{ formItem.valueSuffix }}</span></template>
        </el-input>
        <el-input v-else-if="formItem.elementType==='textarea'" v-model="formItem.value" class="form_item_textarea" :autosize="autosize" :name="formItem.propName" :placeholder="formItem.emptyMessage" type="textarea" :readonly="formItem.elementReadonly" :disabled="formItem.disabled" @change="valueChange" />
        <el-date-picker
          v-else-if="formItem.elementType==='date'&&formItem.pickerType !== 'time'"
          v-model="formItem.dateValue"
          class="date_time_inner"
          :name="formItem.propName"
          :type="formItem.pickerType"
          :format="formItem.textFormatter"
          :default-time="formItem.defaultTime||''"
          :placeholder="formItem.emptyMessage"
          :disabled="formItem.disabled"
          :editable="false"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%;"
          @change="valueChange"
          @focus="datepickerOnFocus"
        />
        <el-time-picker
          v-else-if="formItem.elementType==='date'&&formItem.pickerType === 'time'"
          v-model="formItem.value"
          class="date_time_inner"
          :name="formItem.propName"
          :type="formItem.pickerType"
          :format="formItem.textFormatter"
          :placeholder="formItem.emptyMessage"
          :disabled="formItem.disabled"
          :editable="false"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%;"
          @change="valueChange"
        />

        <el-radio-group v-else-if="formItem.elementType==='radio'" v-model="formItem.value" :disabled="formItem.disabled===true?true:false" :name="formItem.propName" @change="valueChange">
          <el-radio v-for="(option,optKey) in formItem.formatterMap" :key="optKey" :label="option.value">{{ option.text }}</el-radio>
        </el-radio-group>
        <el-checkbox-group v-else-if="formItem.elementType==='checkbox'&&formItem.readonlyShowChecked!==1" v-model="formItem.value" :disabled="formItem.disabled===true?true:false" :name="formItem.propName" @change="valueChange">
          <el-checkbox v-for="(option,optKey) in formItem.formatterMap" :key="optKey" :label="option.value">{{ option.text }}</el-checkbox>
        </el-checkbox-group>
        <div v-else-if="formItem.elementType==='checkbox'&&formItem.readonlyShowChecked===1" v-html="formItem.checkedValue" />
        <el-select v-else-if="formItem.elementType==='select'" v-model="formItem.value" :name="formItem.propName" :disabled="formItem.disabled" :placeholder="'请选择'+formItem.propComment" style="width: 100%;" @change="valueChange">
          <el-option v-for="(option,optKey) in formItem.formatterMap" :key="optKey" :label="option.text" :value="option.value" />
        </el-select>
        <el-date-picker
          v-else-if="formItem.elementType==='datetime'"
          v-model="formItem.value"
          class="date_time_inner"
          :name="formItem.propName"
          :placeholder="formItem.emptyMessage"
          :editable="false"
          :clearable="formItem.clearable"
          type="date"
          style="width: 100%"
          @change="valueChange"
        />
        <!-- formItem.editable -->
      </el-tooltip>
    </validation-provider>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

const moment = require('moment')
import { currency } from '@/global/filters'
import { formatFileSize } from '@/global/utils/index'

export default {
    name: 'FormItem',
    components: {

    },
    props: {
        vo: { type: Object, default: function() { return {} } },
        field: { type: Object, default: function() { return {} } },
        canEdit: { type: Number, default: 1 },
        autosize: { type: Boolean, default: false }
    },
    data: function() {
        return {
            formItem: {},
            fileList: [],
            updateFileList: [],
            encrypted: false
        }
    },
    computed: {
        ...mapGetters([
            'loginUser'
        ])
    },
    watch: {
        canEdit() {
            this.formItem = this.formatElementValue(this.field)
        },
        vo: {
            handler: function(newValue, oldValue) {
                if (this.formItem === undefined || this.formItem.elementType === undefined) return
                let nValue = newValue[this.formItem.propName]
                if (this.formItem.propName.indexOf('.') !== -1) {
                    const propNames = this.formItem.propName.split('.')
                    nValue = newValue[propNames[0]][propNames[1]]
                }
                if (nValue === null || nValue === undefined) return

                if (this.formItem.elementType === 'input' || this.formItem.elementType === 'textarea' || this.formItem.elementType === 'date' || this.formItem.elementType === 'datetime') {
                    let formatter = null
                    if (this.formItem.formatter) {
                        formatter = this.formItem.formatter.replace(/\r\n/g, '').replace(/\n/g, '').replace(/\r/g, '')
                    } else if (this.formItem.textFormatter) {
                        formatter = this.formItem.textFormatter.replace(/\r\n/g, '').replace(/\n/g, '').replace(/\r/g, '')
                    }

                    if (this.formItem.elementCanEdit !== 1 && (this.formItem.elementType === 'date' || this.formItem.elementType === 'datetime')) {
                        const tDate = new Date(nValue.replace(/-/g, '/'))
                        if (!isNaN(tDate.getTime())) {
                            this.$set(this.formItem, 'value', moment(tDate).format(formatter.replace('yyyy', 'YYYY').replace('dd', 'DD')))
                        }
                    } else {
                        this.$set(this.formItem, 'value', nValue)
                    }

                    if (this.formItem.elementType === 'date' || this.formItem.elementType === 'datetime') {
                        if (this.formItem.elementCanEdit === 1) {
                            nValue = moment(new Date(this.formItem.value)).format('YYYY-MM-DD HH:mm:ss')
                            this.$set(this.formItem, 'value', nValue)
                        }
                        this.setDateValue(this.formItem, formatter)
                    }
                } else if (this.formItem.elementType === 'select' || this.formItem.elementType === 'radio' || this.formItem.elementType === 'checkbox') {
                    this.formItem = this.formatElementValue(this.field)
                }

                if (this.formItem.textFormatter === 'currency1' || this.formItem.textFormatter === 'currency2') {
                    if (this.formItem.elementCanEdit === 0 || !this.formItem.elementCanEdit) {
                        if (this.formItem.textFormatter === 'currency1') {
                            this.formItem.value = currency(this.formItem.value)
                        } else {
                            this.formItem.value = (this.formItem.value !== null ? '￥' + Number(this.formItem.value).toFixed(2) : this.formItem.value)
                        }
                    } else {
                        this.formItem.value = (this.formItem.value !== null && !isNaN(Number(this.formItem.value))) ? Number(this.formItem.value).toFixed(2) : this.formItem.value
                    }
                }
            },
            deep: true
        }
    },
    mounted() {

    },
    created() {
        if (this.field.optionGenerateType === 2) {
            this.$http({
                method: this.field.optionGenerateMethod,
                params: { id: this.vo.id, sysCode: this.vo.sysCode || this.loginUser.sysCode },
                url: this.field.optionGenerateUrl
            }).then(res => {
                if (res.code === 'success') {
                    this.vo.passenger[this.field.propName + 'Options'] = res.body.listdata
                    this.field.optionGenerateType = 1
                } else {
                    this.$alert(res.message, '操作提示', { type: 'error' })
                }
                this.initFormItem()
            })
        } else {
            this.initFormItem()
        }
    },
    beforeDestroy() {

    },
    methods: {
        initFormItem() {
            this.formItem = this.formatElementValue(this.field)

            if (this.formItem.value && this.formItem.propType === 'String' && (this.formItem.value.indexOf('{\"enMode\"') === 0)) {
                this.encrypted = true
            }

            if (this.formItem.elementType === 'textarea' && this.formItem.elementCanEdit === 0) {
                this.formItem.className = 'textarea-content'
            }
            if (typeof this.field.resType !== 'undefined' && this.field.propName === 'resRoles') {
                this.vo.passenger.resType = this.field.resType
                this.vo.passenger.pcode = this.field.permissionCode
            }

            if (this.formItem.elementType === 'file' && this.vo[this.formItem.nameField]) {
                let attachHtml = ''
                for (let i = 0; i < 10; i++) {
                    let nameField = this.formItem.nameField
                    let dataField = this.formItem.propName
                    if (i > 0) {
                        dataField += (i + 1)
                        nameField += (i + 1)
                    }
                    var fileName = this.vo[nameField]

                    if (fileName != null) {
                        if (this.formItem.downloadUrl === undefined || this.formItem.downloadUrl === null || this.formItem.downloadUrl === '') {
                            if (this.$vnode.context.moduleInfo) {
                                const updateUrl = this.$vnode.context.moduleInfo.updateUrl
                                let downloadUrl = updateUrl.substring(0, updateUrl.lastIndexOf('/')) + '/download'
                                if (updateUrl.indexOf('?') !== -1) {
                                    downloadUrl += '?' + updateUrl.split('?')[1]
                                }
                                this.formItem.downloadUrl = downloadUrl
                            } else if (this.$vnode.context.wfInstance) {
                                const updateUrl = this.$vnode.context.$vnode.context.wfEngineUrl
                                let downloadUrl = updateUrl + '/download'
                                if (updateUrl.indexOf('?') !== -1) {
                                    downloadUrl += '?' + updateUrl.split('?')[1]
                                }
                                this.formItem.downloadUrl = downloadUrl
                            }
                        }
                        if (this.formItem && this.formItem.downloadUrl.substring(0, 1) !== '/') {
                            this.formItem.downloadUrl = '/' + this.formItem.downloadUrl
                        }
                        var downloadUrl = process.env.VUE_APP_BASE_API + this.formItem.downloadUrl
                        downloadUrl += downloadUrl.indexOf('?') !== -1 ? '&' : '?'
                        downloadUrl += 'id=' + this.vo.id + '&dataField=' + dataField + '&nameField=' + nameField
                        downloadUrl += '&httpPort=' + location.port

                        var fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
                        if (fileType === 'png' || fileType === 'jpg' || fileType === 'jpeg' || fileType === 'gif') {
                            attachHtml += "<img class='img-rview' style='max-width:100px;max-height:100px;' src='" + downloadUrl + "' object-fit='scale-down'/>"
                        } else {
                            attachHtml += "<a href='" + downloadUrl + "' target='_blank'>" + fileName + '</a>'
                        }
                    }
                }
                this.formItem.attachHtml = attachHtml
            } else if (this.formItem.elementType === 'file' && this.formItem.propName.indexOf('formfile') === 0) {
                this.formItem.deleteAttach = 1

                if (this.$vnode.context.$vnode.context.attachments) {
                    let attachHtml = ''
                    this.$vnode.context.$vnode.context.attachments.forEach(attach => {
                        if (attach.fileType.toLowerCase() === this.formItem.attachmentType.toLowerCase()) {
                            let downloadUrl = this.formItem.downloadUrl

                            if (this.$vnode.context.$vnode.context.wfAttachUrl) {
                                downloadUrl = '/' + this.$vnode.context.$vnode.context.wfAttachUrl + '/downloadById'
                            }
                            downloadUrl = process.env.VUE_APP_BASE_API + downloadUrl + '?attachIds=' + attach.id + '&topdf=true&inline=true'
                            attachHtml = "<a href='" + downloadUrl + "' target='_blank'>" + attach.fileName + '</a>'

                            this.formItem.attachHtml = attachHtml
                            this.$set(this.formItem, 'attachId', attach.id)
                        }
                    })
                }
            }

            if (this.formItem.elementType === 'file' && (this.formItem.limitCount === null || this.formItem.limitCount === '' || this.formItem.limitCount === undefined)) this.formItem.limitCount = 1

            if (this.formItem.propComment === undefined || this.formItem.propComment === null) {
                if (this.formItem.emptyMessage !== undefined && this.formItem.emptyMessage !== null) {
                    this.formItem.propComment = this.formItem.emptyMessage.replace('请输入', '').replace('请选择', '')
                } else {
                    this.formItem.propComment = ''
                }
            } else if (!this.formItem.emptyMessage) {
                if (this.formItem.elementType === 'input' || this.formItem.elementType === 'textarea') {
                    this.formItem.emptyMessage = '请输入' + this.formItem.propComment
                } else {
                    this.formItem.emptyMessage = '请选择' + this.formItem.propComment
                }
            }

            if (this.formItem.elementReadonly === 1 || this.formItem.elementReadonly === 'true' || this.formItem.elementReadonly === true) {
                this.formItem.elementReadonly = true
            } else {
                this.formItem.elementReadonly = false
            }

            if (this.formItem.dialog === 1 && this.formItem.dialogRootOrgCode && this.formItem.dialogRootOrgCode !== null && this.formItem.dialogRootOrgCode.substring(0, 3) === 'vo.') {
                const values = this.formItem.dialogRootOrgCode.split('.')
                if (values.length > 2) {
                    this.formItem.dialogRootOrgCode = this.vo[values[1]][values[2]]
                } else {
                    this.formItem.dialogRootOrgCode = this.vo[values[1]]
                }
            }

            if (this.formItem.dialogRootOrgCode === '') {
                delete this.formItem.dialogRootOrgCode
            }

            if (this.formItem.emptyMessage && this.$vnode.context.moduleInfo && this.$i18n.locale !== 'zhCN') {
                let moduleCode = this.$vnode.context.moduleCode
                if (this.$vnode.context.moduleInfo.moduleCode) {
                    moduleCode = this.$vnode.context.moduleInfo.moduleCode
                }

                const expression = moduleCode + '.fields.' + this.formItem.propName
                if (this.$te(expression)) {
                    this.formItem.propComment = this.$t(expression)
                } else {
                    this.formItem.propComment = this.formItem.propName
                }
                this.formItem.emptyMessage = 'Please input ' + this.formItem.propComment.substring(0, 1).toLowerCase() + this.formItem.propComment.substring(1)
            }
        },
        formatElementValue(field) {
            const formItem = JSON.parse(JSON.stringify(this.field))
            if (!formItem.propType) formItem.propType = 'String'

            if (formItem.propName.indexOf('.') === -1) {
                formItem.value = this.vo[formItem.propName]
            } else {
                const propNames = formItem.propName.split('.')

                formItem.value = this.vo[propNames[0]][propNames[1]]
            }

            if (formItem.value === null && formItem.defaultValue != null && formItem.defaultValue !== '') {
                formItem.value = formItem.defaultValue

                if (formItem.propName.indexOf('.') === -1) {
                    this.vo[formItem.propName] = formItem.value
                } else {
                    const propNames = formItem.propName.split('.')
                    this.vo[propNames[0]][propNames[1]] = formItem.value
                }
            }

            if (formItem.elementCanEdit === '{{canEdit}}' || formItem.elementCanEdit === '{${canEdit}}' || formItem.elementCanEdit === '{{curTN.tnCanEdit}}' || formItem.elementCanEdit === '{${curTN.tnCanEdit}}' || formItem.elementCanEdit === '{${formula}}') {
                if (this.canEdit === 1 || this.canEdit === true) {
                    formItem.elementCanEdit = 1
                } else {
                    formItem.elementCanEdit = 0
                }
            } else {
                formItem.elementCanEdit = parseInt(this.field.elementCanEdit)
            }

            if ((formItem.elementType !== 'input' && formItem.elementType !== 'textarea') || formItem.valueMaxLength === 'null' || formItem.valueMaxLength === undefined) {
                formItem.valueMaxLength = null
            }
            if ((formItem.elementType !== 'input' && formItem.elementType !== 'textarea') || formItem.valueMinLength === 'null' || formItem.valueMinLength === undefined) {
                formItem.valueMinLength = null
            }

            formItem.isPhone = false
            formItem.isEmail = false
            formItem.isNumber = false
            formItem.isInteger = false
            formItem.isCurrency = false
            formItem.isIdentity = false

            if (formItem.textFormatter === 'phone') {
                formItem.isPhone = true
            } else if (formItem.textFormatter === 'email') {
                formItem.isEmail = true
            } else if (formItem.textFormatter === 'number' || formItem.propType === 'Short' || formItem.propType === 'Long' || formItem.textFormatter === 'Short' || formItem.textFormatter === 'Long') {
                formItem.isNumber = true
            } else if ((formItem.propType === 'Integer' && (formItem.textFormatter === undefined || formItem.textFormatter === null || formItem.textFormatter.toLowerCase() === 'integer')) || (formItem.textFormatter && formItem.textFormatter.toLowerCase() === 'integer')) {
                formItem.isInteger = true
            } else if (formItem.textFormatter === 'card') {
                formItem.isIdentity = true
            }

            if (formItem.elementType === 'radio' || formItem.elementType === 'select') {
                formItem.isInteger = false
                formItem.isNumber = false
                if (formItem.value !== null)formItem.value += ''
            }
            if (formItem.elementType === 'checkbox') formItem.isNumber = false

            if (formItem.textFormatter === 'currency1' || formItem.textFormatter === 'currency2') {
                formItem.isNumber = true
                if (formItem.elementCanEdit === 0 || !formItem.elementCanEdit) {
                    if (formItem.textFormatter === 'currency1') {
                        formItem.value = currency(formItem.value)
                    } else {
                        formItem.value = (formItem.value !== null ? '￥' + Number(formItem.value).toFixed(2) : formItem.value)
                    }
                } else {
                    formItem.value = (formItem.value !== null && !isNaN(Number(formItem.value))) ? Number(formItem.value).toFixed(2) : formItem.value
                }
            }

            if (!formItem.formatterMap && (formItem.elementType === 'checkbox' || formItem.elementType === 'radio' || formItem.elementType === 'select')) {
                if (this.vo.passenger !== undefined && typeof this.vo.passenger[formItem.propName + 'Options'] === 'object' && this.vo.passenger[formItem.propName + 'Options'].length > 0) {
                    formItem.formatterMap = this.vo.passenger[formItem.propName + 'Options']
                }
            }
            if (!formItem.formatterMap) {
                var colFormater = formItem.propFormatter
                if (typeof colFormater === 'undefined' || colFormater === null || colFormater === '') colFormater = formItem.elementFormatter
                const formatterMap = formItem.formatterMap || []
                if (colFormater !== undefined && colFormater != null && colFormater !== '' && !formItem.formatterMap) {
                    if (formItem.option !== undefined && typeof formItem.option === 'object' && formItem.option.length > 0) {
                        for (let i = 0; i < formItem.option.length; i++) {
                            formatterMap.push({ 'text': formItem.option[i].name, 'value': formItem.option[i].value })
                        }
                    } else {
                        const formatters = colFormater.replace(/\r\n/g, '<br>').replace(/\\r\\n/g, '<br>').replace(/\n/g, '<br>').split('<br>')
                        for (let i = 0; i < formatters.length; i++) {
                            if (formatters[i].split('：').length > 1) {
                                const v = formatters[i].split('：')[0]

                                formatterMap.push({ 'text': formatters[i].split('：')[1], 'value': v })
                            }
                        }
                    }

                    if (formItem.propType === 'boolean') {
                        formItem.value = formItem.value ? '1' : '0'
                    }
                }
                formItem.formatterMap = formatterMap
            }

            if (formItem.formatterMap) {
                formItem.formatterMap.forEach(item => {
                    if (!isNaN(item.value)) {
                        item.value += ''
                    }
                })
            }

            if (formItem.elementType === 'checkbox') {
                if (formItem.value === null) {
                    formItem.value = []
                } else if (typeof formItem.value === 'string') {
                    formItem.value = formItem.value.split(',')
                }

                if (formItem.elementCanEdit === 1) {
                    formItem.readonlyShowChecked = 0
                }
                if (formItem.readonlyShowChecked === 1 && formItem.formatterMap) {
                    formItem.isRequired = false
                    let values = ''
                    for (let i = 0; i < formItem.value.length; i++) {
                        formItem.formatterMap.forEach(item => {
                            if ((formItem.value[i] + '') === (item.value + '')) {
                                if (values === '') {
                                    values = item.text
                                } else {
                                    values += '、' + item.text
                                }
                            }
                        })
                    }

                    formItem.checkedValue = values
                }
            }

            if ((this.canEdit === 1 || this.canEdit === true) && this.$vnode.context.curTN && this.$vnode.context.curTN.nodeFormFields) {
                const nodeFormFields = this.$vnode.context.curTN.nodeFormFields
                for (let i = 0; i < nodeFormFields.length; i++) {
                    if (nodeFormFields[i].propCode === formItem.propName) {
                        formItem.elementCanEdit = nodeFormFields[i].isEditable

                        if (formItem.isRequired !== nodeFormFields[i].isRequired) {
                            formItem.isRequired = nodeFormFields[i].isRequired
                            const tdlbl = this.$vnode.context.$refs['tdlbl_' + formItem.propComment]
                            if (tdlbl !== undefined) {
                                if (formItem.isRequired === 1) {
                                    if (tdlbl.innerHTML.indexOf('class="required"') === -1) {
                                        tdlbl.innerHTML = '<span class="required">*</span>' + tdlbl.innerHTML
                                    }
                                } else {
                                    if (tdlbl.innerHTML.indexOf('class="required"') !== -1) {
                                        tdlbl.innerHTML = formItem.propComment
                                    }
                                }
                            }
                        }

                        break
                    }
                }
            }

            if (formItem.onClickEvent !== undefined && formItem.onClickEvent !== null && formItem.onClickEvent.indexOf('can-edit=') === 0) {
                let canEditFlag = formItem.onClickEvent.split('can-edit=')[1]
                if (canEditFlag.substring(0, 1) === '"' && canEditFlag.substring(canEditFlag.length - 1) === '"') {
                    canEditFlag = canEditFlag.substring(1, canEditFlag.length - 1)
                }
                formItem.elementCanEdit = parseInt(this.$vnode.context[canEditFlag])
            }

            // formatterMap[0].text=='t',代表在系统中添加的临时列表项（单选、复选、下拉 ）映射，实际值程序运行时动态设置
            if (formItem.elementCanEdit !== 1 && formItem.formatterMap.length > 0 && formItem.formatterMap[0].text !== 't') {
                if (formItem.elementType === 'radio' || formItem.elementType === 'checkbox') {
                    formItem.disabled = true
                } else {
                    const options = formItem.formatterMap.filter(item => {
                        if (formItem.value === (item.value + '')) return true
                    })
                    if (options.length > 0) {
                        formItem.value = options[0].text
                    }
                }
            }

            if (formItem.elementCanEdit !== 1 && formItem.elementType === 'textarea' && formItem.value !== null && formItem.value !== undefined) {
                formItem.value = formItem.value.replace(/\r\n/g, '<br>').replace(/\n/g, '<br>')
            }

            if (formItem.elementType === 'date') {
                let formatter = formItem.textFormatter
                if (formItem.pickerType === undefined || formItem.pickerType === '' || formItem.pickerType === null) {
                    if (formatter === null || formatter.trim() === '') {
                        formItem.pickerType = 'datetime'
                    } else if (formatter.split(' ').length > 1) {
                        formItem.pickerType = 'datetime'
                    } else if (formatter.split(':').length > 1) {
                        formItem.pickerType = 'time'
                    } else {
                        formItem.pickerType = 'date'
                    }
                }
                if (formItem.pickerType === 'datetime' && !formItem.defaultTime) {
                    if (formItem.propName.indexOf('start') === 0) {
                        formItem.defaultTime = '08:00:00'
                    } else if (formItem.propName.indexOf('end') === 0) {
                        formItem.defaultTime = '20:00:00'
                    }
                }

                if (formItem.value !== undefined && formItem.value !== null && formItem.value !== '' && formatter !== null && formatter.trim() !== null && formatter.trim() !== '') {
                    formatter = formatter.replace(/\r\n/g, '').replace(/\n/g, '').replace(/\r/g, '')

                    if (formItem.elementCanEdit === 0) {
                        const tDate = new Date(formItem.value.replace(/-/g, '/'))
                        if (!isNaN(tDate.getTime())) {
                            formItem.value = moment(tDate).format(formatter.replace('yyyy', 'YYYY').replace('dd', 'DD'))
                        }
                    } else if (formItem.propType === 'String') {
                        if (formItem.pickerType === 'time') {
                            if (formItem.value.length === 5) {
                                if (formatter.toLowerCase() === 'hh:mm') {
                                    formItem.value = '0000-00-00 ' + formItem.value + ':00'
                                }
                            } else if (formItem.value.length === 8) {
                                formItem.value = '0000-00-00 ' + formItem.value
                            }
                        } else {
                            if (formItem.value.length === 10) {
                                formItem.value = formItem.value + ' 00:00:00'
                            } else if (formItem.value.length === 16) {
                                formItem.value = formItem.value + ':00'
                            }
                        }
                    }

                    this.setDateValue(formItem, formatter)
                }
            }
            if (formItem.valueSuffix === undefined || formItem.valueSuffix === null || formItem.valueSuffix === 'null') {
                formItem.valueSuffix = ''
            }

            return formItem
        },
        setDateValue(formItem, formatter) {
            if (formItem.weekday === 1 && formItem.value !== null && formItem.value !== '' && formatter.indexOf('dd') !== -1) {
                if (formItem.value.indexOf('星期') > -1)formItem.value = formItem.value.split(' 星期')[0]
                const tDate = new Date(formItem.value.replace(/-/g, '/').replace('年', '/').replace('月', '/').replace('日', ''))
                const weekday = { 0: '日', 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六' }[moment(tDate).day()]
                formItem.dateValue = formItem.value + ' 星期' + weekday

                if (formatter.indexOf('星期') !== -1) {
                    formatter = formatter.split(' 星期')[0]
                }

                formItem.textFormatter = formatter + ' 星期' + weekday
            } else {
                formItem.dateValue = formItem.value
            }
            this.$forceUpdate()
        },
        valueChange(val) {
            if (this.formItem.elementType !== 'checkbox' && (this.formItem.propType === 'Short' || this.formItem.propType === 'Integer' || this.formItem.propType === 'Long')) {
                if (!isNaN(parseInt(val))) {
                    val = parseInt(val)
                }
            }
            if (this.formItem.elementType === 'checkbox') {
                for (let i = 0; i < val.length; i++) {
                    if (val[i] === '')val.splice(i--, 1)
                }
                val = val.join(',')
            }

            if ((this.formItem.elementType === 'date' || this.formItem.elementType === 'datetime') && this.formItem.textFormatter) {
                if (this.formItem.textFormatter.indexOf(' 星期') !== -1) {
                    val = val.split(' 星期')[0]
                    this.formItem.value = val
                }
                this.setDateValue(this.formItem, this.formItem.textFormatter.split(' 星期')[0])
            }

            if (this.formItem.propName.indexOf('.') === -1) {
                // this.vo[this.formItem.propName] = val
                this.$set(this.vo, this.formItem.propName, val)
            } else {
                const propNames = this.formItem.propName.split('.')
                // this.vo[propNames[0]][propNames[1]] = val
                this.$set(this.vo[propNames[0]], propNames[1], val)
            }

            if (this.formItem.onClickEvent !== undefined && this.formItem.onClickEvent !== null && this.formItem.onClickEvent.indexOf('@change=') === 0) {
                let func = this.formItem.onClickEvent.trim().split('=')[1]

                if (func.substring(0, 1) === '"' && func.substring(func.length - 1) === '"') {
                    func = func.substring(1, func.length - 1)
                }
                if (func.substring(0, 1) === '\'' && func.substring(func.length - 1) === '\'') {
                    func = func.substring(1, func.length - 1)
                }
                if (this.$vnode.context[func] !== undefined) {
                    this.$vnode.context[func](val, this.formItem)
                } else if (this.$vnode.context.wfInstance && this.$vnode.context.$vnode.context[func] !== undefined) {
                    this.$vnode.context.$vnode.context[func](val, this.formItem)
                }
            }
        },
        datepickerOnFocus() {
            if (this.formItem.textFormatter.indexOf(' 星期')) {
                this.formItem.textFormatter = this.formItem.textFormatter.split(' 星期')[0]
            }
        },
        itemOnClick() {
            if (this.formItem.onClickEvent !== undefined && this.formItem.onClickEvent !== null &&
                (this.formItem.onClickEvent.indexOf('@click=') === 0 || this.formItem.onClickEvent.indexOf('@focus=') === 0)) {
                let func = this.formItem.onClickEvent.trim().split('=')[1]

                if (func.substring(0, 1) === '"' && func.substring(func.length - 1) === '"') {
                    func = func.substring(1, func.length - 1)
                }
                if (func.substring(0, 1) === '\'' && func.substring(func.length - 1) === '\'') {
                    func = func.substring(1, func.length - 1)
                }

                if (this.$vnode.context[func] !== undefined) {
                    this.$vnode.context[func](this.formItem)
                } else if (this.$vnode.context.wfInstance && this.$vnode.context.$vnode.context[func] !== undefined) {
                    this.$vnode.context.$vnode.context[func](this.formItem)
                }
            }
        },
        handleResRolesChange(resRoles) {
            this.vo.passenger.resRoles = resRoles
        },
        handleUploadClick() {
            this.updateFileList = []
        },
        handleUploadChange(file, fileList) {
            if (this.updateFileList.length === Number(this.formItem.limitCount)) {
                return
            }
            this.formItem.pid = this.vo.id
            this.updateFileList.push(file)

            if (this.$vnode.context.$vnode.context.attachments) {
                const attach = {}
                attach.fileName = file.name
                attach.fileSize = formatFileSize(file.size)
                attach.fileType = this.formItem.attachmentType
                attach.uploadBy = this.$vnode.context.loginUser.personName
                attach.uploadTime = '待上传'
                attach.file = file
                attach.checked = false
                file.progress = 0

                this.$vnode.context.$vnode.context.attachments.push(attach)
            } else if (this.$vnode.context.moduleInfo) {
                let moduleCode = this.$vnode.context.moduleCode
                if (this.$vnode.context.moduleInfo.moduleCode) {
                    moduleCode = this.$vnode.context.moduleInfo.moduleCode
                }
                this.$bus.emit('addUploadFiles', this.formItem, this.updateFileList, moduleCode)
            } else if (this.$vnode.context.addUploadFiles) {
                this.$bus.emit('addUploadFiles', this.formItem, this.updateFileList, this.$vnode.context.moduleCode)
            }

            let fileNames = ''
            this.updateFileList.forEach(file => {
                if (fileNames === '') {
                    fileNames = file.name
                } else {
                    fileNames += '、' + file.name
                }
            })

            if (this.formItem.nameField.indexOf('.') === -1) {
                this.vo[this.formItem.nameField] = fileNames
            } else {
                const propNames = this.formItem.nameField.split('.')
                this.vo[propNames[0]][propNames[1]] = fileNames
            }

            this.fileList = this.updateFileList
        },
        handleUploadError(err, file, fileList) {
            this.$message({
                showClose: true,
                message: err.message,
                type: 'error',
                dangerouslyUseHTMLString: true
            })
        },
        removeFormfile(id) {
            this.$confirm('您是否确认删除已上传的文件？', '确认操作', { type: 'warning' })
                .then(async() => {
                    document.querySelector('.removeBodyfileIcon').innerHTML = '&nbsp;正在删除...'

                    let wfAttachUrl = this.formItem.downloadUrl.replace('/downloadById', '').replace('/download', '') + '/deleteAttach'

                    if (this.$vnode.context.$vnode.context.wfAttachUrl) {
                        wfAttachUrl = this.$vnode.context.$vnode.context.wfAttachUrl + '/delete'
                    }

                    this.$http({
                        method: 'DELETE',
                        contentType: 'application/x-www-form-urlencoded',
                        params: { attachIds: id },
                        url: wfAttachUrl
                    }).then(res => {
                        if (res.code === 'success') {
                            if (this.$vnode.context.$vnode.context.attachments) {
                                for (var i = 0; i < this.$vnode.context.$vnode.context.attachments.length; i++) {
                                    if (this.$vnode.context.$vnode.context.attachments[i].id === id) {
                                        this.$vnode.context.$vnode.context.attachments.splice(i--, 1)
                                    }
                                }
                            }

                            delete this.formItem.attachHtml
                            this.$forceUpdate()
                        } else {
                            this.$alert(res.message, '操作提示', { type: 'error' })
                        }
                    })
                })
        },
        openListitemDialog() {
            this.$http({
                method: this.formItem.optionGenerateMethod,
                params: { id: this.vo.id, sysCode: this.vo.sysCode || this.loginUser.sysCode },
                url: this.formItem.optionGenerateUrl
            }).then(res => {
                if (res.code === 'success') {
                    this.$bus.emit('openListitemDialog', this.formItem.dialogTitle, res.body.listdata, rst => {
                        if (rst.code === 'success') {
                            const func = 'onSelectListitemCompleted'
                            if (this.$vnode.context[func] !== undefined) {
                                this.$vnode.context[func](this.value, { name: this.model })
                            } else {
                                this.formItem.value = rst.value.join('，')
                                this.$set(this.vo, this.formItem.propName, this.formItem.value)
                            }
                        }
                    }, this.formItem.value, this.formItem.propComment, null, this.formItem.dialogMultiple)
                } else {
                    this.$alert(res.message, '操作提示', { type: 'error' })
                }
            })
        },
        decryptData(model) {
            this.$app.decryptData(this.vo[model]).then(res => {
                if (res.code === 'success') {
                    this.$set(this.vo, model, res.body.data)
                    this.encrypted = false
                } else {
                    this.$alert(res.message, { type: 'error' })
                }
            })
        }
    }
}
</Script>

<style lang="scss">
.form_item{
    .el-date-editor .el-input__prefix{
        right:5px;
        left:auto;
    }
    .el-input--prefix .el-input__inner{
        cursor:pointer;
        padding-left:5px !important;
    }
    .date_time_inner{
        .el-input__inner{padding-left:25px!important;padding-right:25px;}
        .el-input__prefix{left:0px;right: auto;}
    }
    .form_item_textarea{
        textarea{
            min-height: 70px!important;
        }
    }
    .input_suffix{
        line-height: 36px;
    }
}
</style>

<style lang="scss" scoped>
    span {
        white-space: pre-wrap;
    }
    /deep/ .el-upload--text{
        width:100%
    }
    /deep/ .el-divider--horizontal{
        margin:10px 0
    }
</style>
